package design.factory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

public class JDKProxy {
    private static Logger logger = LoggerFactory.getLogger(JDKProxy.class);

    public static <T> T getProxy(ICacheAdapter cacheAdapter) throws Exception {
        //获得代理对象JDKInvocationHandler
        InvocationHandler handler = new JDKInvocationHandler(cacheAdapter);
        //负责把磁盘上的.class文件加载到JVM内存中
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        //获得接口文件
        Class<?>[] classes = cacheAdapter.getClass().getInterfaces();

        logger.info("classes.size:{},classes[0]:{}",classes.length,classes[0]);

        //调用方法会先调用handler的invoke方法
        return (T) Proxy.newProxyInstance(classLoader, new Class[]{classes[0]}, handler);
    }
}
